require('dotenv').config();
const express = require('express');
const cors = require('cors');
const axios = require('axios');

const app = express();
const PORT = process.env.PORT1 || 4588;

// 中间件
app.use(cors());
app.use(express.json());

// AI 聊天接口
app.post('/ai-chat', async (req, res) => {
  try {
    const { messages } = req.body;
    if (!messages || !Array.isArray(messages)) {
      return res.status(400).json({ error: '请求参数错误：messages 应为数组' });
    }

    const requestBody = {
      model: 'generalv3',
      messages,
      stream: false,
      max_tokens: 1024,
    };

    const response = await axios.post(
      'https://spark-api-open.xf-yun.com/v1/chat/completions',
      requestBody,
      {
        headers: {
          'Authorization': `Bearer ${process.env.XFYUN_API_KEY1}`,
          'Content-Type': 'application/json',
        }
      }
    );

    res.json(response.data);
  } catch (error) {
    console.error('❌ AI 请求出错:', error.response?.data || error.message || error);
    res.status(500).json({
      error: 'AI 服务请求失败',
      detail: error.response?.data || error.message,
    });
  }
});

// 启动服务
app.listen(PORT, () => {
  console.log(`🚀 AI 服务已启动： http://localhost:${PORT}`);
});
